package com.liu.stockmarket.ui.fund

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import com.liu.stockmarket.MainViewModel
import com.liu.stockmarket.R
import com.liu.stockmarket.StockMarketApplication
import com.liu.stockmarket.databinding.FragmentFundBinding
import com.liu.stockmarket.databinding.HeaderOrderItemBinding
import com.liu.stockmarket.databinding.HeaderStockSummaryBinding
import com.liu.stockmarket.model.HoldingStockProfit
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import com.liu.stockmarket.ui.detail.DetailActivity
import com.liu.stockmarket.ui.kline.KlineActivity
import com.liu.stockmarket.ui.search.SearchActivity
import com.liu.stockmarket.ui.search.SearchResultAdapter
import com.liu.stockmarket.ui.stock.HoldingStockAdapter
import com.liu.stockmarket.ui.stock.add.StockAddActivity
import com.liu.stockmarket.ui.stock.modify.StockModifyActivity
import com.liu.stockmarket.utils.*
import com.lxj.xpopup.XPopup
import org.apache.commons.lang3.math.NumberUtils
import java.math.BigDecimal
import java.time.LocalDate

/**
 * 基金
 */
class FundFragment : Fragment() {

    private lateinit var fundViewModel: FundViewModel
    private var _binding: FragmentFundBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private lateinit var mAdapter: HoldingStockAdapter

    private var _headerStockSummaryBinding: HeaderStockSummaryBinding? = null

    private val headerStockSummaryBinding get() = _headerStockSummaryBinding!!


    private lateinit var headerOrderItemBinding: HeaderOrderItemBinding

    private lateinit var holdingStockList: List<StockEntity>
    private val mainViewModel: MainViewModel by activityViewModels()


    // 要复制的代码都不是好代码,迟早要重构你
    private var spinnerOrderType = -1
    private var spinnerOrderItem = -1

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {


        val stockMarketApplication = this.requireActivity().application as StockMarketApplication

        fundViewModel =
            ViewModelProvider(
                this, FundViewModel.FundViewModelFactory(
                    stockMarketApplication.transactionRecordRepository,
                    stockMarketApplication.stockRepository,
                    stockMarketApplication.easyMoneyRepository
                )
            ).get(FundViewModel::class.java)

        _binding = FragmentFundBinding.inflate(inflater, container, false)
        _headerStockSummaryBinding = HeaderStockSummaryBinding.inflate(inflater, container, false)
        headerOrderItemBinding = HeaderOrderItemBinding.inflate(inflater, container, false)

        val root: View = binding.root


        mAdapter = HoldingStockAdapter()


        // 设置头部
        mAdapter.addHeaderView(headerStockSummaryBinding.root.rootView)
        mAdapter.addHeaderView(headerOrderItemBinding.root.rootView, 1)

        with(binding.rvList) {
            adapter = mAdapter
        }

        observer()
        listener()


        binding.swipeLayout.setColorSchemeColors(Color.argb(100, 255, 152, 0))

        initTwoSpinner()
        return root
    }

    private fun observer() {
        fundViewModel.allFund.observe(this.viewLifecycleOwner) {

//
            this.holdingStockList = it

            binding.swipeLayout.isRefreshing = true
            onRefresh()

        }

        fundViewModel.result.observe(this.viewLifecycleOwner) {
            if (it.isSuccess()) {
                val list = it.data?.list ?: mutableListOf()
                mAdapter.setList(list.filter { item ->
                    // 不显示清仓
                    item.holdingNumber != BigDecimal.ZERO

                }.sort(spinnerOrderType, spinnerOrderItem))
                setHeader(it.data?.header)
            } else {
                mAdapter.setList(mutableListOf())
                mAdapter.setEmptyView(R.layout.rv_empty_view)
                this.requireContext().toast("请求数据失败：${it.message}")
            }
            binding.swipeLayout.isRefreshing = false
        }

    }

    private fun listener() {
        binding.add.setOnClickListener {
            SearchActivity.start(this.requireContext())
        }

        binding.swipeLayout.setOnRefreshListener {

            onRefresh()

        }
        binding.rvList.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            mainViewModel.setShowDataCenterButton(scrollY <= oldScrollY)
        }
        mAdapter.setOnItemLongClickListener(
            HoldingStockAdapter.OnItemLongClickListener(
                this.requireContext(),
                onTransactionListener = { stock ->
                    StockAddActivity.start(this.requireContext(), stock)

                },
                onKlineListener = { stock ->
                    KlineActivity.start(
                        requireContext(),
                        stock.code.getKlineCode(stock.stockType, stock.transactionExchange),
                        stock.name,
                        stock.transactionExchange.getKlineType()
                    )

                },
                onDeleteListener = { stockId ->
                    fundViewModel.deleteByStockId(stockId)
                },onModifyListener = { id, name, code, price, number ->
                    StockModifyActivity.start(this.requireContext(), id, name, code, price, number)
                }, onDividendListener = { stock,holdingPrice, holdingNumber ->
                    XPopup.Builder(this.requireContext())
                        .asInputConfirm("${stock.name} 分红", "", "", "请输入每股分红金额", {
                            if (!NumberUtils.isCreatable(it)) {
                                this.requireContext().toast("请输入有效数字")
                                return@asInputConfirm
                            }
                            val transactionRecordEntity = TransactionRecordEntity(
                                id = null,
                                stockId = stock.id!!,
                                transactionType = TransactionRecordEntity.TransactionType.DIVIDENDS,
                                transactionDate = LocalDate.now(),
                                transactionPrice = BigDecimal(it),
                                transactionNumber = holdingNumber,
                                handlingFee = BigDecimal.ZERO,
                            )
                            fundViewModel.saveDividends(transactionRecordEntity)
                            fundViewModel.save(stock.id!!,holdingPrice-BigDecimal(it),holdingNumber)
                            this.requireContext().toast("保存分红成功")
                        }, {

                        }, R.layout.popup_number_input).show()

                })
        )

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as HoldingStockAdapter.Item
            DetailActivity.start(this.requireContext(), item.stockId)

        }
        headerOrderItemBinding.spinnerOrderType.onItemSelectedListener = object :
            AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                spinnerOrderType = position
                val preferences =
                    this@FundFragment.requireActivity().getPreferences(Context.MODE_PRIVATE)
                with(preferences.edit()) {
                    putInt(ORDER_TYPE_KEY, position)
                    apply()
                }
                mAdapter.setList(mAdapter.data.sort(spinnerOrderType, spinnerOrderItem))
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

        }
        headerOrderItemBinding.spinnerOrderItem.onItemSelectedListener = object :
            AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                spinnerOrderItem = position
                val preferences =
                    this@FundFragment.requireActivity().getPreferences(Context.MODE_PRIVATE)
                with(preferences.edit()) {
                    putInt(ORDER_ITEM_KEY, position)
                    apply()
                }
                mAdapter.setList(mAdapter.data.sort(spinnerOrderType, spinnerOrderItem))
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

        }
    }

    private fun initTwoSpinner() {
        val preferences = this.requireActivity().getPreferences(Context.MODE_PRIVATE)
        spinnerOrderType = preferences.getInt(ORDER_TYPE_KEY, -1)
        spinnerOrderItem = preferences.getInt(ORDER_ITEM_KEY, -1)

        headerOrderItemBinding.spinnerOrderType.setSelection(if (spinnerOrderType != -1) spinnerOrderType else 0)
        headerOrderItemBinding.spinnerOrderItem.setSelection(if (spinnerOrderItem != -1) spinnerOrderItem else 0)

    }

    // 获取股票交易数据，暂不考虑休市时间问题
    private fun onRefresh() {
        if (!holdingStockList.isNullOrEmpty()) {
            fundViewModel.getFundTransaction()
        } else {
            mAdapter.setList(mutableListOf())
            mAdapter.setEmptyView(R.layout.rv_empty_view)
            binding.swipeLayout.isRefreshing = false
        }

    }

    private fun setHeader(header: HoldingStockProfit.Header?) {


        header?.let {
            // 累计
            val accumulativeProfit = it.accumulativeProfit.setScale(5)

            val accumulativeProfitPercent = it.accumulativeProfitPercent





            with(headerStockSummaryBinding) {
                this.tvAllHoldingMoney.text = it.allHoldingMoney.getString()
                this.tvTodayAllProfit.money(requireContext(), it.todayAllProfit)
                this.tvTodayAllProfitPercent.percent(
                    requireContext(),
                    it.todayAllProfitPercent
                )
                this.tvAllProfit.money(requireContext(), it.allProfit)
                this.tvAllProfitPercent.percent(
                    requireContext(),
                    it.allProfitPercent
                )

                this.tvAccumulativeProfit.money(requireContext(), accumulativeProfit)
                this.tvAccumulativeProfitPercent.percent(
                    requireContext(),
                    accumulativeProfitPercent
                )
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        const val ORDER_TYPE_KEY = "fundOrderType"
        const val ORDER_ITEM_KEY = "fundOrderItem"
    }
}